package com.junlinpro.config;

import java.util.Date;
import java.util.Map;

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import com.junlinpro.entity.MessageEntity;
import com.junlinpro.utils.Constant;
import com.junlinpro.utils.DateUtil;
import com.junlinpro.utils.MessageUtil;
import com.junlinpro.utils.SocketChannelMap;

import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;

/**
 * 定时任务配置
 */
@Configuration
@EnableScheduling
public class TimingConfig {

    @Scheduled(cron = "0 0/1 * * * ?")
    public void sendHeartbeat() {
        Map<String, Channel> heartbeatMap = SocketChannelMap.getHeartbeatChannelMap();
        if (heartbeatMap != null && heartbeatMap.size() > 0) {
            for (Map.Entry entry : heartbeatMap.entrySet()) {
                if (entry != null) {
                    String key = (String) entry.getKey();
                    Channel channel = (Channel) entry.getValue();
                    MessageEntity msg = new MessageEntity();
                    msg.setCardId(Integer.parseInt(key));
                    byte channelId = 0x00;
                    msg.setChannelId(channelId);
                    byte cmd = 0x05;
                    msg.setCmd(cmd);
                    msg.setAllLen(23);
                    msg.setVersionNum(Constant.HARDWARE_VERSION);
                    msg.setFrameId(0);
                    msg.setCardType((byte) 0x00);
                    int utcTimeStamp = DateUtil.transForMilliSecond(new Date());
                    msg.setOccurTime(utcTimeStamp);
                    byte[] byteMsg = MessageUtil.rtnMessageTobyte(msg);
                    channel.writeAndFlush(Unpooled.copiedBuffer(byteMsg));
                }
            }
            System.out.println("--- 下发心跳 ---");
        } else {
            System.out.println("--- 暂时没有维护的心跳 ---");
        }
    }

}
